class Solution {
public:
    std::vector<int> nextGreaterElements(std::vector<int>& nums) {
        std::stack<int> stack; // 存储下标
        int n = nums.size();
        std::vector<int> res(n, -1); // 初始化结果数组，全部为-1
        for (int i = 0; i < n; ++i) {
            while (!stack.empty() && nums[i] > nums[stack.top()]) {
                res[stack.top()] = nums[i];
                stack.pop();
            }
            stack.push(i);
        }
        for (int i = 0; i < n; ++i) {
            while (!stack.empty() && nums[i] > nums[stack.top()]) {
                res[stack.top()] = nums[i];
                stack.pop();
            }
            stack.push(i);
        }
        return res;
    }
};